
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Emberjs,Ember-Teach,Ember-Object," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>计算属性（compute properties） [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        计算属性（compute properties）
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:37.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Object/" rel="tag">Ember-Object</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Teach/" rel="tag">Ember-Teach</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Emberjs/" rel="tag">Emberjs</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 8 分钟</span>
    </header>

    <div class="post-content">
      <h3 id="简单的计算属性"><a href="#简单的计算属性" class="headerlink" title="简单的计算属性"></a>简单的计算属性</h3><p>简单地来说，计算属性就是将函数声明为属性，就类似于调用了一个函数，<code>Ember</code>会自动调用这个函数。计算属性最大的特点就是能自动检测变化，及时更新数据。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">Person = Ember.Object.extend(&#123;</span><br><span class="line">    firstName: <span class="literal">null</span>,</span><br><span class="line">    lastName: <span class="literal">null</span>,</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//  fullName 就是一个计算属性</span></span><br><span class="line">    fullName: Ember.computed(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;lastName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;firstName&#x27;</span>) + <span class="string">&quot;, &quot;</span> + <span class="built_in">this</span>.get(<span class="string">&#x27;lastName&#x27;</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//  实例化同时传入参数</span></span><br><span class="line"><span class="keyword">var</span> piter = Person.create(&#123;</span><br><span class="line">    firstName: <span class="string">&#x27;chen&#x27;</span>,</span><br><span class="line">    lastName: <span class="string">&#x27;ubuntuvim&#x27;</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(piter.get(<span class="string">&#x27;fullName&#x27;</span>));  <span class="comment">// output &gt;&gt;   chen, ubuntuvim</span></span><br></pre></td></tr></table></figure>

<p>计算属性其实就是一个函数，如果你接触过就<code>jQuery、Extjs</code>相信你回非常熟悉，在这两个框架中函数就是这么定义的。只不过在<code>Ember</code>中，把这种函数当做属性来处理，并且可以通过get获取函数的返回值。</p>
<h3 id="计算属性链"><a href="#计算属性链" class="headerlink" title="计算属性链"></a>计算属性链</h3><p>在<code>Ember</code>程序中，计算属性还能调用另外一个计算属性，形成计算属性链，也可以用于扩展某个方法。在上一实例的基础上增加一个<code>description()</code>方法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">Person = Ember.Object.extend(&#123;</span><br><span class="line">    firstName: <span class="literal">null</span>,</span><br><span class="line">    lastName: <span class="literal">null</span>,</span><br><span class="line">    age: <span class="literal">null</span>,</span><br><span class="line">    county: <span class="literal">null</span>,</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//  fullName 就是一个计算属性</span></span><br><span class="line">    fullName: Ember.computed(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;lastName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;firstName&#x27;</span>) + <span class="string">&quot;, &quot;</span> + <span class="built_in">this</span>.get(<span class="string">&#x27;lastName&#x27;</span>);</span><br><span class="line">    &#125;),</span><br><span class="line">    description: Ember.computed(<span class="string">&#x27;fullName&#x27;</span>, <span class="string">&#x27;age&#x27;</span>, <span class="string">&#x27;county&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;fullName&#x27;</span>) + <span class="string">&quot; age &quot;</span> + <span class="built_in">this</span>.get(<span class="string">&#x27;age&#x27;</span>) + <span class="string">&quot; county &quot;</span> + <span class="built_in">this</span>.get(<span class="string">&#x27;county&#x27;</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//  实例化同时传入参数</span></span><br><span class="line"><span class="keyword">var</span> piter = Person.create(&#123;</span><br><span class="line">    firstName: <span class="string">&#x27;chen&#x27;</span>,</span><br><span class="line">    lastName: <span class="string">&#x27;ubuntuvim&#x27;</span>,</span><br><span class="line">    age: <span class="number">25</span>,</span><br><span class="line">    county: <span class="string">&#x27;china&#x27;</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(piter.get(<span class="string">&#x27;description&#x27;</span>));  <span class="comment">// output &gt;&gt;   chen, ubuntuvim</span></span><br></pre></td></tr></table></figure>

<p>当用户使用<code>set</code>方法改变<code>firstName</code>的值，然后再调用<code>get(&#39;description&#39;)</code>得到的值也是更新后的值。</p>
<h3 id="重写计算属性的get、set方法"><a href="#重写计算属性的get、set方法" class="headerlink" title="重写计算属性的get、set方法"></a>重写计算属性的get、set方法</h3><p>注意要把重写的属性作为参数传入<code>computed</code>方法，要区别计算属性的定义方法，定义的时候<code>computed</code>方法的最后一个参数是一个<code>function</code>，而重写的时候最后一个参数是一个<code>hash</code>。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//    重写计算属性的get、set方法</span></span><br><span class="line">Person = Ember.Object.extend(&#123;</span><br><span class="line">    firstName: <span class="literal">null</span>,</span><br><span class="line">    lastName: <span class="literal">null</span>,</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//  重写计算属性fullName的get、set方法</span></span><br><span class="line">    fullName: Ember.computed(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;lastName&#x27;</span>, &#123;</span><br><span class="line">        get(key) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;firstName&#x27;</span>) + <span class="string">&quot;,&quot;</span> + <span class="built_in">this</span>.get(<span class="string">&#x27;lastName&#x27;</span>);</span><br><span class="line">        &#125;,</span><br><span class="line">        set(key, value) &#123;</span><br><span class="line">            <span class="comment">//  这个官方文档使用的代码，但是我运行的时候出现 Uncaught SyntaxError: Unexpected token [  这个错误，不知道是否是缺少某个文件，后续会补上；</span></span><br><span class="line"><span class="comment">//            console.log(&quot;value = &quot; + value);</span></span><br><span class="line"><span class="comment">//            var [ firstName, lastName ] = value.split(/\s+/);  </span></span><br><span class="line">            <span class="keyword">var</span> firstName = value.split(<span class="regexp">/\s+/</span>)[<span class="number">0</span>];</span><br><span class="line">            <span class="keyword">var</span> lastName = value.split(<span class="regexp">/\s+/</span>)[<span class="number">1</span>];</span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;firstName&#x27;</span>, firstName);</span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;lastName&#x27;</span>, lastName);</span><br><span class="line">            </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;),</span><br><span class="line"><span class="comment">//    对于普通的属性无法重写get、set方法</span></span><br><span class="line"><span class="comment">//    firstName: Ember.computed(&#x27;firstName&#x27;, &#123;</span></span><br><span class="line"><span class="comment">//        get(key) &#123;</span></span><br><span class="line"><span class="comment">//            return this.get(&#x27;firstName&#x27;) + &quot;@@&quot;;</span></span><br><span class="line"><span class="comment">//        &#125;,</span></span><br><span class="line"><span class="comment">//        set(key, value) &#123;</span></span><br><span class="line"><span class="comment">//            this.set(&#x27;firstName&#x27;, value);</span></span><br><span class="line"><span class="comment">//        &#125;</span></span><br><span class="line"><span class="comment">//    &#125;)</span></span><br><span class="line">&#125;);</span><br><span class="line">    </span><br><span class="line"><span class="keyword">var</span> jack = Person.create();    </span><br><span class="line">jack.set(<span class="string">&#x27;fullName&#x27;</span>, <span class="string">&quot;james kobe&quot;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(jack.get(<span class="string">&#x27;firstName&#x27;</span>));</span><br><span class="line"><span class="built_in">console</span>.log(jack.get(<span class="string">&#x27;lastName&#x27;</span>));</span><br></pre></td></tr></table></figure>

<p><img src="http://static.oschina.net/uploads/img/201509/08100319_16q9.png" alt="运行结果"></p>
<h3 id="计算属性值的统计"><a href="#计算属性值的统计" class="headerlink" title="计算属性值的统计"></a>计算属性值的统计</h3><p>我们经常会遇到这种情况：某个计算属性值是依赖某个数组或者其他对象的，比如在<code>Ember</code>的<code>todos</code>这个例子中有这样的一段代码。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line">  todos: [</span><br><span class="line">    Ember.Object.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span> &#125;),</span><br><span class="line">    Ember.Object.create(&#123; <span class="attr">isDone</span>: <span class="literal">false</span> &#125;),</span><br><span class="line">    Ember.Object.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span> &#125;)</span><br><span class="line">  ],</span><br><span class="line">  remaining: Ember.computed(<span class="string">&#x27;todos.@each.isDone&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> todos = <span class="built_in">this</span>.get(<span class="string">&#x27;todos&#x27;</span>);</span><br><span class="line">    <span class="keyword">return</span> todos.filterBy(<span class="string">&#x27;isDone&#x27;</span>, <span class="literal">false</span>).get(<span class="string">&#x27;length&#x27;</span>);</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>计算属性<code>remaining</code>的值于依赖数组<code>todos</code>。在这里还有个知识点：在上述代码<code>computed()</code>方法里有一个<code>todos.@each.isDone</code>这样的键，里面包含了一个特别的键<code>@each</code>（后面还会看到更特别的键<code>[]</code>）。需要注意的是这种键不能嵌套并且是只能获取一个层次的属性。比如<code>todos.@each.foo.name</code>(获取多层次属性，这里是先得到foo再获取<code>name</code>)或者<code>todos.@each.owner.@each.name</code>(嵌套)这两种方式都是不允许的。</p>
<p>在如下4种情况<code>Ember</code>会自动更新绑定的计算属性值：<br><br>1.在<code>todos</code>数组中任意一个对象的<code>isDone</code>属性值发生变化的时候；<br>2.往<code>todos</code>数组新增元素的时候；<br>3.从<code>todos</code>数组删除元素的时候；<br>4.在控制器中<code>todos</code>数组被改变为其他的数组的时候；</p>
<p>比如下面代码演示的结果；</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line">Task = Ember.Object.extend(&#123;</span><br><span class="line">  isDone: <span class="literal">false</span>  <span class="comment">//  默认为false</span></span><br><span class="line">&#125;); </span><br><span class="line"></span><br><span class="line">WorkerLists = Ember.Object.extend(&#123;</span><br><span class="line">  <span class="comment">//  定义一个Task对象数组</span></span><br><span class="line">  lists: [</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">false</span> &#125;),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span> &#125;),</span><br><span class="line">    Task.create(),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span> &#125;),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span> &#125;),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span> &#125;),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">false</span> &#125;),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span> &#125;)</span><br><span class="line">  ],</span><br><span class="line"></span><br><span class="line">  remaining: Ember.computed(<span class="string">&#x27;lists.@each.isDone&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> lists = <span class="built_in">this</span>.get(<span class="string">&#x27;lists&#x27;</span>);</span><br><span class="line">    <span class="comment">//  先查询属性isDone值为false的对象，再返回其数量</span></span><br><span class="line">    <span class="keyword">return</span> lists.filterBy(<span class="string">&#x27;isDone&#x27;</span>, <span class="literal">false</span>).get(<span class="string">&#x27;length&#x27;</span>);</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 如下代码使用到的API请查看：http://emberjs.com/api/classes/Ember.MutableArray.html</span></span><br><span class="line"><span class="keyword">var</span> wl = WorkerLists.create();</span><br><span class="line"><span class="comment">//  所有isDone属性值未做任何修改</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;1,&gt;&gt; Not complete lenght is &#x27;</span> + wl.get(<span class="string">&#x27;remaining&#x27;</span>));  <span class="comment">//  output 3</span></span><br><span class="line"><span class="keyword">var</span> lists = wl.get(<span class="string">&#x27;lists&#x27;</span>);  <span class="comment">//  得到对象内的数组</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// -----  演示第一种情况： 1. 在todos数组中任意一个对象的isDone属性值发生变化的时候；</span></span><br><span class="line"><span class="comment">//  修改数组一个元素的isDone的 值</span></span><br><span class="line"><span class="keyword">var</span> item1 = lists.objectAt(<span class="number">3</span>);  <span class="comment">//  得到第4个元素 objectAt()方法是Ember为我们提供的</span></span><br><span class="line"><span class="comment">// console.log(&#x27;item1 = &#x27; + item1);</span></span><br><span class="line">item1.set(<span class="string">&#x27;isDone&#x27;</span>, <span class="literal">false</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;2,&gt;&gt; Not complete lenght is &#x27;</span> + wl.get(<span class="string">&#x27;remaining&#x27;</span>));  <span class="comment">//  output 4</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//  --------- 2.  往todos数组新增元素的时候；</span></span><br><span class="line">lists.pushObject(Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">false</span> &#125;));  <span class="comment">//新增一个isDone为false的对象</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;3,&gt;&gt; Not complete lenght is &#x27;</span> + wl.get(<span class="string">&#x27;remaining&#x27;</span>));  <span class="comment">//  output 5</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//  --------- 3.  从todos数组删除元素的时候；</span></span><br><span class="line">lists.removeObject(item1);  <span class="comment">// 删除了一个元素</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;4,&gt;&gt; Not complete lenght is &#x27;</span> + wl.get(<span class="string">&#x27;remaining&#x27;</span>));  <span class="comment">//  output 4</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//  --------- 4.  在控制器中todos数组被改变为其他的数组的时候；</span></span><br><span class="line"><span class="comment">//  创建一个Controller</span></span><br><span class="line">TodosController = Ember.Controller.extend(&#123;</span><br><span class="line">  <span class="comment">// 在控制器内定义另外一个Task对象数组</span></span><br><span class="line">  todosInController: [</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">false</span> &#125;),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span> &#125;)</span><br><span class="line">  ],</span><br><span class="line">  <span class="comment">//  使用键”@each.isDone“遍历得到的filterBy()方法过滤后的对象的isDone属性</span></span><br><span class="line">  remaining: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">//  remaining()方法返回的是控制器内的数组</span></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;todosInController&#x27;</span>).filterBy(<span class="string">&#x27;isDone&#x27;</span>, <span class="literal">false</span>).get(<span class="string">&#x27;length&#x27;</span>);</span><br><span class="line">  &#125;.property(<span class="string">&#x27;@each.isDone&#x27;</span>)  <span class="comment">//  指定遍历的属性</span></span><br><span class="line">&#125;);</span><br><span class="line">todosController = TodosController.create();</span><br><span class="line"><span class="keyword">var</span> count = todosController.get(<span class="string">&#x27;remaining&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;5,&gt;&gt; Not complete lenght is &#x27;</span> + count);  <span class="comment">//  output 1</span></span><br></pre></td></tr></table></figure>

<p><img src="http://static.oschina.net/uploads/img/201509/08100320_d33w.png" alt="代码演示的结果"></p>
<p>上述的情况中，我们对数组对象的是关注点是在对象的属性上，但是实际中往往很多情况我们并不关系对象内的属性是否变化了，而是把数组元素作为一个整体对象处理（比如数组元素个数的变化）。相比上述的代码下面的代码检测的是数组对象元素的变化，而不是对象的<code>isDone</code>属性的变化。在这种情况你可以看看下面例子，在例子中使用键<code>[]</code>代替键<code>@each</code>。从键的变化也可以看出他们的不同之处。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">Task = Ember.Object.extend(&#123;</span><br><span class="line">  isDone: <span class="literal">false</span>,  <span class="comment">//  默认为false</span></span><br><span class="line">  name: <span class="string">&#x27;taskName&#x27;</span>,</span><br><span class="line">  <span class="comment">//  为了显示结果方便，重写toString()方法</span></span><br><span class="line">  toString: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;[name = &#x27;</span>+<span class="built_in">this</span>.get(<span class="string">&#x27;name&#x27;</span>)+<span class="string">&#x27;, isDone = &#x27;</span>+<span class="built_in">this</span>.get(<span class="string">&#x27;isDone&#x27;</span>)+<span class="string">&#x27;]&#x27;</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;); </span><br><span class="line"></span><br><span class="line">WorkerLists = Ember.Object.extend(&#123;</span><br><span class="line">  <span class="comment">//  定义一个Task对象数组</span></span><br><span class="line">  lists: [</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">false</span>, <span class="attr">name</span>: <span class="string">&#x27;ibeginner.sinaapp.com&#x27;</span> &#125;),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span>, <span class="attr">name</span>: <span class="string">&#x27;i2cao.xyz&#x27;</span> &#125;),</span><br><span class="line">    Task.create(),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span>, <span class="attr">name</span>: <span class="string">&#x27;ubuntuvim&#x27;</span> &#125;),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span> , <span class="attr">name</span>: <span class="string">&#x27;1527254027@qq.com&#x27;</span>&#125;),</span><br><span class="line">    Task.create(&#123; <span class="attr">isDone</span>: <span class="literal">true</span> &#125;)</span><br><span class="line">  ],</span><br><span class="line"></span><br><span class="line">  index: <span class="literal">null</span>,</span><br><span class="line">  indexOfSelectedTodo: Ember.computed(<span class="string">&#x27;index&#x27;</span>, <span class="string">&#x27;lists.[]&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;lists&#x27;</span>).objectAt(<span class="built_in">this</span>.get(<span class="string">&#x27;index&#x27;</span>));</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> wl = WorkerLists.create();</span><br><span class="line"><span class="comment">//  所有isDone属性值未做任何修改</span></span><br><span class="line"><span class="keyword">var</span> index = <span class="number">1</span>;</span><br><span class="line">wl.set(<span class="string">&#x27;index&#x27;</span>, index);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;Get &#x27;</span>+wl.get(<span class="string">&#x27;indexOfSelectedTodo&#x27;</span>).toString()+<span class="string">&#x27; by index &#x27;</span> + index);</span><br></pre></td></tr></table></figure>

<p><img src="http://static.oschina.net/uploads/img/201509/08100320_HZ9I.png" alt="代码演示的结果"></p>
<p><code>Ember.computed</code>这个组件中有很多使用键<code>[]</code>实现的方法。当你想创建一个计算属性是数组的时候特别适用。你可以使用<code>Ember.computed.map</code>来构建你的计算属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Hamster = Ember.Object.extend(&#123;</span><br><span class="line">  chores: <span class="literal">null</span>,</span><br><span class="line">  excitingChores: Ember.computed(<span class="string">&#x27;chores.[]&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="comment">//告诉Ember chores是一个数组</span></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;chores&#x27;</span>).map(<span class="function"><span class="keyword">function</span>(<span class="params">chore, index</span>) </span>&#123;</span><br><span class="line">      <span class="comment">//return `$&#123;index&#125; --&gt; $&#123;chore.toUpperCase()&#125;`;  //  可以使用$&#123;&#125;表达式，并且在表达式内可以直接调用js方法</span></span><br><span class="line">      <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;chore&#125;</span>`</span>;  <span class="comment">//返回元素值</span></span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//  为数组赋值</span></span><br><span class="line"><span class="keyword">const</span> hamster = Hamster.create(&#123;</span><br><span class="line">  <span class="comment">//  名字chores要与类Hamster定义指定数组的名字一致</span></span><br><span class="line">  chores: [<span class="string">&#x27;First Value&#x27;</span>, <span class="string">&#x27;write more unit tests&#x27;</span>]</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(hamster.get(<span class="string">&#x27;excitingChores&#x27;</span>));</span><br><span class="line">hamster.get(<span class="string">&#x27;chores&#x27;</span>).pushObject(<span class="string">&quot;Add item test&quot;</span>);  <span class="comment">//add an item to chores array</span></span><br><span class="line"><span class="built_in">console</span>.log(hamster.get(<span class="string">&#x27;excitingChores&#x27;</span>));</span><br></pre></td></tr></table></figure>

<p><code>Ember</code>还提供了另外一种方式去定义数组类型的计算属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Hamster = Ember.Object.extend(&#123;</span><br><span class="line">  chores: <span class="literal">null</span>,</span><br><span class="line">  excitingChores: Ember.computed(<span class="string">&#x27;chores.[]&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;chores&#x27;</span>).map(<span class="function"><span class="keyword">function</span>(<span class="params">chore, index</span>) </span>&#123;</span><br><span class="line">      <span class="comment">//return `$&#123;index&#125; --&gt; $&#123;chore.toUpperCase()&#125;`;  //  可以使用$&#123;&#125;表达式，并且在表达式内可以直接调用js方法</span></span><br><span class="line">      <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;chore&#125;</span>`</span>;  <span class="comment">//返回元素值</span></span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//  为数组赋值</span></span><br><span class="line"><span class="keyword">const</span> hamster = Hamster.create(&#123;</span><br><span class="line">  <span class="comment">//  名字chores要与类Hamster定义指定数组的名字一致</span></span><br><span class="line">  chores: [<span class="string">&#x27;First Value&#x27;</span>, <span class="string">&#x27;write more unit tests&#x27;</span>]</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(hamster.get(<span class="string">&#x27;excitingChores&#x27;</span>));</span><br><span class="line">hamster.get(<span class="string">&#x27;chores&#x27;</span>).pushObject(<span class="string">&quot;Add item test&quot;</span>);  <span class="comment">//add an item to chores array</span></span><br><span class="line"><span class="built_in">console</span>.log(hamster.get(<span class="string">&#x27;excitingChores&#x27;</span>));</span><br></pre></td></tr></table></figure>

<br>
博文完整代码放在[Github](https://github.com/ubuntuvim/my_emberjs_code)（博文经过多次修改，博文上的代码与github代码可能又出入，不过影响不大！），如果你觉得博文对你有点用在github项目上给我个`star`吧。您的肯定对我来说是最大的动力！！


    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/01/18/ember-teach/components/%E5%B1%9E%E6%80%A7%E4%BC%A0%E9%80%92/" rel="next" title="属性传递">
          属性传递
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/ember-teach/components/%E5%8C%85%E8%A3%B9%E5%86%85%E5%AE%B9/" rel="prev" title="包裹内容">
            包裹内容
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%AE%80%E5%8D%95%E7%9A%84%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7"><span class="toc-text">简单的计算属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%E9%93%BE"><span class="toc-text">计算属性链</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%87%8D%E5%86%99%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%E7%9A%84get%E3%80%81set%E6%96%B9%E6%B3%95"><span class="toc-text">重写计算属性的get、set方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%E5%80%BC%E7%9A%84%E7%BB%9F%E8%AE%A1"><span class="toc-text">计算属性值的统计</span></a></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: '计算属性（compute properties）', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
